from flask import Blueprint, request, jsonify
import json
from conf.comm import sqlalchemy_context
from database import *
from math import ceil

bp_lianxi = Blueprint('lianxixi', __name__)


@bp_lianxi.route('/add', methods=['POST', 'GET', 'DELETE', 'PUT'])
def add():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        cates = cate(name=data['name'])
        db.session.add(cates)
        db.session.commit()
        return jsonify({'code': 200})
    elif request.method == 'GET':
        cpage = int(request.args.get('cpage'))
        page_size = 2
        start = (cpage - 1) * page_size
        nacte = cate.query.offset(start).limit(page_size)
        # catess = cate.query.all()
        tpage = cate.query.count()
        total = ceil(tpage/page_size)
        list = []
        for i in nacte:
            dict = {}
            dict['id'] = i.id
            dict['name'] = i.name
            list.append(dict)
        return jsonify({'code': 200, "list": list, "total": total})
    elif request.method == 'DELETE':
        id = request.args.get('id')
        cate.query.filter_by(id=id).delete()
        db.session.commit()
        return jsonify({'code': 200})
    elif request.methaod == 'PUT':
        id = request.args.get('id')
        name = request.args.get('name')
        cate.query.filter_by(id=id).update({'name': name})
        db.session.commit()
        return jsonify({'code': 200})
